def word():
    global lst
    global word_list
    lst = []
    word_list = []
    with open("Walden.txt", "r+", encoding="utf-8") as fp:
        import re
        a = fp.read()
        # 将大写转换为小写
        lower_word = a.lower()
        # 替换文中的特殊字符
        b = re.sub(r'[\d",\n/?+:.;$-]', ' ', lower_word)
        c = b.split(" ")
        # print(c)
        for i in c:
            # 去除文中的空格,将单词存入列表里
            if i == '' or i == '--':
                pass
            else:
                lst.append(i)

        word_list = lst.copy()


word()


def count():
    global dict_words
    global count_words
    count_words = 0
    dict_words = {}
    # 计数文中单词出现次数，并存入dict_words字典
    for i in word_list:
        count_words = word_list.count(i)
        dict1 = {i: count_words}
        dict_words.update(dict1)
    # 输出结果
    print(dict_words)


count()


# 将结果存入文件
def result():
    with open("result.txt", "w+", encoding="utf-8") as f:
        for i in dict_words:
            f.write(f"{i}出现次数为{dict_words[i]}次\n")


result()
